package com.mdinic.blogovi.front.page.person;

import org.apache.wicket.markup.html.form.EmailTextField;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.UrlValidator;

import com.mdinic.blogovi.front.common.AbstractFormFeedbackPanel;
import com.mdinic.blogovi.front.page.BSession;
import com.mdinic.blogovi.model.Person;
import com.mdinic.blogovi.service.PersonService;
import com.mdinic.blogovi.service.model.UpdatePersonResult;

public class PersonEditPanel extends AbstractFormFeedbackPanel<Person> {

    private static final long serialVersionUID = 1L;

    @SpringBean
    private PersonService personService;

    public PersonEditPanel(String id) {
        super(id, getPerson());

        getForm().add(new TextField<String>(Person.NICKNAME).setRequired(true));
        getForm().add(new TextField<String>(Person.FIRSTNAME).setRequired(true));
        getForm().add(new TextField<String>(Person.LASTNAME).setRequired(true));

        getForm().add(new EmailTextField(Person.EMAIL));

        getForm().add(new TextField<String>(Person.BLOG).add(new UrlValidator()));
        getForm().add(new TextField<String>(Person.WEBSITE).add(new UrlValidator()));

        getForm().add(new PasswordTextField(Person.PASSWORD).setRequired(false));
        getForm().add(new PasswordTextField(Person.CONFIRM_PASSWORD).setRequired(false));
    }

    private static Person getPerson() {
        Person person = BSession.get().getPerson();
        Person p = new Person();
        p.setFirstname(person.getFirstname());
        p.setLastname(person.getLastname());
        p.setNickname(person.getNickname());
        p.setBlog(person.getBlog());
        p.setWebsite(person.getWebsite());
        p.setId(person.getId());
        return p;
    }

    @Override
    protected void submit(Person object) {
        UpdatePersonResult result = personService.updatePerson(object);
        switch (result.getType()) {
        case OK:

            BSession.get().setPerson(result.getPerson());

            PageParameters userParameters = new PageParameters();
            userParameters.add(PersonViewPage.URL_PARAM_NAME, object.getId());
            setResponsePage(PersonViewPage.class, userParameters);
            break;
        case EMAIL_TAKEN:
            error("E-mail je zauzet.");
            break;

        case NICKNAME_TAKEN:
            error("Nadimak je zauzet.");
            break;
        case PASSWORDS_DO_NOT_MATCH:
            error("Lozinke se ne slazu");
            break;
        case PASSWORD_WEAK:
            error("Lozinka mora sadrzati 1 cifru, 1 malo slovo, 1 veliko slovo ukupne duzine od 6 do 20.");
            break;
        default:
            throw new IllegalStateException(result.getType().toString());
        }

    }

}
